package com.bblocks.message.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.image.ImageClient;
import cn.jpush.api.image.model.ImageType;
import cn.jpush.api.image.model.ImageUploadResult;
import cn.jpush.api.image.model.ImageUrlPayload;
import com.bblocks.exception.ServiceException;
import com.bblocks.message.api.JMessageClient;
import com.bblocks.message.api.common.model.RegisterInfo;
import com.bblocks.message.api.common.model.cross.CrossGroup;
import com.bblocks.message.api.group.CreateGroupResult;
import com.bblocks.message.api.group.GroupInfoResult;
import com.bblocks.message.api.group.MemberListResult;
import com.bblocks.message.api.group.MemberResult;
import com.bblocks.message.api.resource.UploadResult;
import com.bblocks.message.api.user.UserGroupsResult;
import com.bblocks.message.api.user.UserInfoResult;
import com.bblocks.message.api.user.UserStateListResult;
import com.bblocks.message.api.utils.GuardUtils;
import com.bblocks.message.service.ImUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * 文档：https://docs.jiguang.cn/jmessage/server/rest_api_im/#group
 * @author: xingdong
 * @time: 2020/6/20 下午4:45
 */

@Slf4j
@Service
public class ImUserServiceImpl implements ImUserService {

    private final JMessageClient client = new JMessageClient(GuardUtils.appkey.getValue(), GuardUtils.masterSecret.getValue());
    
    private final ImageClient imageClient = new ImageClient(GuardUtils.masterSecret.getValue(), GuardUtils.appkey.getValue());

    @Override
    public String registerUsers(List<RegisterInfo.Builder> users) {
        String res = "";
        try {
            List<RegisterInfo> registerInfos = users.stream().map(user -> user.build()).collect(Collectors.toList());
            RegisterInfo[] regUsers = new RegisterInfo[registerInfos.size()];
            res = client.registerUsers(registerInfos.toArray(regUsers));
            log.info(res);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }
        return res;
    }

    @Override
    public UploadResult uploadFileForIm(String path, String fileType) {
        UploadResult result = new UploadResult();
        try {
            result = client.uploadFile(path, fileType);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }
        return result;
    }
    
    public ImageUploadResult uploadImageByUrl(String imageUrl) throws APIConnectionException, APIRequestException {
    	ImageUrlPayload  payload = ImageUrlPayload.newBuilder()
		.setImageType(ImageType.LARGE_ICON)
		.setImageUrl(imageUrl)
		.build();
        return imageClient.uploadImage(payload);
	}
    
    @Override
    public void deleteUser(String username) {
    	try {
			client.deleteUser(username);
		} catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }
    }

    public boolean isExistUser(String username) {
        boolean flag = true;
        try {
            UserInfoResult userInfoResult  = client.getUserInfo(username);
            if (null == userInfoResult) {
                flag = false;
            }
        } catch (Exception e) {
            log.error("查询极光账号异常", e);
            flag = false;
        }
        return flag;
    }

    @Override
    public boolean isExistUser(String[] usernames) {
    	boolean flag = true;
    	try {
    		UserStateListResult[] userStateList = client.getUsersState(usernames);
    		if (userStateList == null || userStateList.length==0) {
    			flag = false; 
			}

    		for (UserStateListResult userStateListResult : userStateList) {
    			log.info("isExistUser:=============="+userStateListResult.toString());
				if (CollectionUtils.isEmpty(userStateListResult.getDevices())) {
					return false;
				}
				for (UserStateListResult.Device device : userStateListResult.getDevices()) {
					if (device.getLogin()) {
						flag = true;
						break;
					}
					flag = false;
				}
			}
    	} catch (Exception e) {
            flag = false;
        }
    	return flag;
    }
    
    @Override
    public UserInfoResult getUserInfo(String username) {
    	UserInfoResult userInfoResult = null;
    	try {
    		userInfoResult = client.getUserInfo(username);
		} catch (APIConnectionException e) {
			log.error(e.getMessage());
		} catch (APIRequestException e) {
			log.error(e.getMessage());
		}
    	return userInfoResult;
    }

    /**
     * 1 - 私有群（默认）
     * 2 - 公开群
     * @param owner 群主
     * @param gname
     * @param desc
     * @param avatar
     * @param flag  1 - 私有群（默认） 2 - 公开群
     * @return
     */
    public String createGroup(String owner, String gname, String desc,  String avatar,int flag){

        try {
            String[] userlist = {};
            CreateGroupResult groupResult = client.createGroup(owner, gname, desc, avatar, flag, userlist);

           // groupResult.getResponseCode();

            return String.valueOf(groupResult.getGid());
        } catch (APIConnectionException e) {
            log.error("开群："+gname+" 环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("开群："+gname+" 环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }

    public void joinGroup(String groupNo,List<String> userNos){
        CrossGroup[] groupAdds = new CrossGroup[1];

        CrossGroup.Builder addUser = new CrossGroup.Builder();
        addUser.setAddUsers(userNos.stream().toArray(size -> new String[size]));
        addUser.setAppKey(GuardUtils.appkey.getValue());
        //addUser.setAppKey(key);

        CrossGroup groupOne =  addUser.build();
        groupAdds[0] = groupOne;
        try {
            log.info(" groupAdds:{}",groupAdds);
            client.addOrRemoveCrossGroupMember(Long.parseLong(groupNo),groupAdds);
        } catch (APIConnectionException e) {
            log.error("入群："+groupNo+" 环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("入群："+groupNo+" 环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }

    public void quitGroup(String groupNo,List<String> userNos){
        CrossGroup[] groupRemoves = new CrossGroup[1];

        CrossGroup.Builder removeUser = new CrossGroup.Builder();
        removeUser.setRemoveUsers(userNos.stream().toArray(size -> new String[size]));
        removeUser.setAppKey(GuardUtils.appkey.getValue());

        CrossGroup groupOne =  removeUser.build();
        groupRemoves[0] = groupOne;
        try {
            client.addOrRemoveCrossGroupMember(Long.parseLong(groupNo),groupRemoves);
        } catch (APIConnectionException e) {
            log.error("退群："+groupNo+" 环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("退群："+groupNo+" 环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }

    public GroupInfoResult groupInfo(String groupNo){
        try {
            GroupInfoResult result = client.getGroupInfo(Long.parseLong(groupNo));
            return result;
        } catch (APIConnectionException e) {
            log.error("群信息："+groupNo+" 环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("群信息："+groupNo+" 环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }

    public MemberResult[]  groupUserList(String groupNo){
        try {
            MemberListResult result = client.getGroupMembers(Long.parseLong(groupNo));


            return result.getMembers();
        } catch (APIConnectionException e) {
            log.error("群成员："+groupNo+" 环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("群成员："+groupNo+" 环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }

    public GroupInfoResult[] userGroupList(String userNo){
        try {
            UserGroupsResult result = client.getGroupListByUser(userNo);
            return result.getGroups();
        } catch (APIConnectionException e) {
            log.error("用户："+userNo+" 群列表环信通讯异常： ", e);
            throw new ServiceException("通讯异常，请稍后再试！");
        } catch (APIRequestException e) {
            log.error("用户："+userNo+" 群列表环信业务异常： ", e);
            throw new ServiceException("系统故障，请稍后再试！");
        }
    }


}
